<template>
  <!--  监测点管理-->
  <div class="page">
    <div class="detail-header">
      {{projectDetail.name}}/{{workPointName}}
    </div>
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-form ref="form" label-width="80px" :inline="true">
        <el-form-item label="监测对象">
          <el-select v-model="form.workPointId" filterable clearable placeholder="选择监测对象" style="width: 160px">
            <el-option v-for="item in workPointList2" :key="item.id" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-input v-model="form.name" clearable placeholder="监测点名称" style="width: 260px">
        <template slot="prepend">监测点名称</template>
      </el-input>
      <el-input v-model="form.equipSn" clearable placeholder="输入设备编号" style="width: 260px">
        <template slot="prepend">设备编号</template>
      </el-input>
      <el-select v-model.trim="form.monitorType" clearable placeholder="选择监测类型" style="width: 140px">
        <el-option v-for="item in EnumProjectMonitorTypeList" :key="item.code" :label="item.name"
                   :value="item.code"></el-option>
      </el-select>
      <el-select v-model.trim="form.warningLevel" clearable placeholder="选择预警等级" style="width: 140px">
        <el-option v-for="item in EnumWarningLevelList" :key="item.code" :label="item.name"
                   :value="item.code"></el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page = 1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="el-icon-plus" @click.stop="handleAddMonitorPoint" class="common_btn-small"
                 :disabled="!hasPermission('project:monitorPoint:add')"
      >
        新建监测点
      </el-button>
      <el-button icon="el-icon-sort" @click.stop="handleSortMonitorPoint" class="common_btn-small"
                 :disabled="!hasPermission('project:monitorPoint:add')"
      >
        监测点排序
      </el-button>
      <!-- table -->
      <el-table :data="tableList" border>
        <el-table-column label="序号" type="index" width="70">
        </el-table-column>
        <el-table-column prop="name" label="监测点名称" min-width="220"></el-table-column>
        <el-table-column prop="monitorTypeName" label="监测类型" min-width="160">
          <template slot-scope="scope">
            <i style="color: #1990FE" class="iconfont" :class="scope.row.monitorType | gradeMonitorType"></i>
            {{scope.row.monitorTypeName}}
          </template>
        </el-table-column>
        <el-table-column prop="bindEquipSn" label="设备编号" min-width="160">
          <template slot-scope="scope">
            {{scope.row.bindEquipSn?scope.row.bindEquipSn:'未绑定设备'}}
            <el-popover
              placement="top-start"
              width="220"
              trigger="click">
              <p class="sensor_label">测点关联的设备信息
              <p>
              <p class="sensor_info">设备外壳：{{scope.row.caseCode}}</p>
              <p class="sensor_info" v-for="item in scope.row.monitorPointSensorList" :key="item.id">
                传感器SN：{{item.sensorSn}}</p>
              <button slot="reference">
                <i style="margin-left: 5px;font-size: 15px;color: #1990FE" class="el-icon-warning"
                   v-if="scope.row.bindEquipSn"></i></button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="warningLevelName" label="预警等级" width="105">
          <template slot-scope="scope">
            <el-tag size="mini" :style="scope.row.warningLevel | gradeColor1">{{scope.row.warningLevelName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isAutoRecord" label="监测方式" min-width="140">
          <template slot-scope="scope">
            <el-tag size="mini" :style="scope.row.isAutoRecord| gradeColor" style="color: white">
              {{scope.row.isAutoRecord | monitorMethod}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="collectionTime" width="170" label="最新数据时间">
          <template slot-scope="scope">
            {{scope.row.collectionTime | formatTimer }}
          </template>
        </el-table-column>
        <el-table-column prop="collectionTime" width="170" label="更新时间">
          <template slot-scope="scope">
            {{scope.row.updateTime | formatTimer }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="280">
          <template slot-scope="scope">
            <el-button type="text" class="btn_add"
                       :disabled="!hasPermission('project:monitorPoint:add')"
                       @click="handleEditMonitorPoint(scope.row)">
              编辑
            </el-button>
            <!--   人工监测不展示-->
            <el-button v-if="scope.row.isAutoRecord === 1" type="text" class="btn_edit"
                       :disabled="!hasPermission('project:monitorPoint:add')"
                       @click="bindingDevice(scope.row)">绑定设备
            </el-button>
            <el-button v-if="scope.row.isAutoRecord === 0&&scope.row.monitorType==1
" type="text" class="btn_edit"
                       :disabled="!hasPermission('project:monitorPoint:add')"
                       @click="importBaseData(scope.row)">导入基准数据
            </el-button>
            <!--  展示导入数据按钮-->
            <el-button v-if="scope.row.isAutoRecord !== 1&&scope.row.isAutoRecord !== 3" type="text" class="btn_edit"

                       :disabled="!hasPermission('project:monitorPoint:add')"
                       @click="importData(scope.row)">导入数据
            </el-button>
            <el-button type="text" class="btn_jump" @click="toControl(scope.row)">
              查看监测数据
            </el-button>
            <el-button type="text" @click="handleDelete(scope.row)" class="btn_delete"
                       :disabled="!hasPermission('project:monitorPoint:delete')">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize" :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                     layout="sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <!--    监测点删除-->
    <el-dialog title="监测点删除确认" :visible.sync="isDelShowDialog" :close-on-click-modal="false" width="220px">
      <div style="text-align: center;color:#ff4d51;margin-bottom: 10px;font-size: 15px">
        警告：监测点删除后，相关的监测数据将会随之清空！！！
      </div>
      <el-form label-suffix="：" label-position="right" ref="deleteConfirm" :rules="rules" :model="deleteConfirm"
               label-width="0px"
               class="work-point-form">
        <el-form-item prop="mark">
          <el-input v-model="deleteConfirm.mark" placeholder="请输入‘删除’字符，进行确认"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isDelShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>
    <!-- 监测点 排序窗口  -->
    <el-dialog title="监测点排序" :visible.sync="isShowDialog" :close-on-click-modal="false" width="220px">
      <div style="text-align: center;color: #ff4d51;margin-bottom: 10px;font-size: 15px">
        从上至下进行排序，拖拽改变顺序，放至边框边缘进行上下滑动，提交后生效！
      </div>
      <div style="height: 500px;overflow: auto;border: 2px solid #1990FE">
        <el-tree
          :data="monitorSortList"
          node-key="id"
          default-expand-all
          highlight-current
          :allow-drop="allowDrop"
          draggable>
        <span class="custom-tree-node" slot-scope="{ node }">
            <span>
                <i class="el-icon-s-flag" style="margin-right: 10px;color: #1990FE"></i>{{ node.label }}
            </span>
        </span>
        </el-tree>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="sortSubmit">确定</el-button>
      </span>
    </el-dialog>
    <!-- 监测点 新增编辑弹窗  -->
    <el-drawer
      :title="editMonitorTitle"
      :visible.sync="newForm"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
      size="60%">
      <div class="demo-drawer__content">
        <form-add-edit @update="reFlesh" ref="monitorPoint"></form-add-edit>
      </div>
      <div class="demo-drawer__footer">
        <el-button type="primary" class=" common_btn-defalut" @click="submitMonitor">确 定</el-button>
      </div>
    </el-drawer>
    <!-- 监测点绑定设备  -->
    <el-drawer
      title="监测点关联设备"
      :visible.sync="showBindingDevice"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
      size="60%">
      <div class="demo-drawer__content">
        <sensor-relation @update="reFlesh" ref="sensorRelation"></sensor-relation>
      </div>
      <div class="demo-drawer__footer">
        <el-button type="info" @click="showBindingDevice=false">取 消</el-button>
        <el-popconfirm confirmButtonText='好的' cancelButtonText='不用了' icon="" title="解绑后数据将不会采集，确定解绑吗？"
                       @confirm="unboundEquip">
          <el-button slot="reference" type="warning" style="margin: 0px 20px">解绑设备</el-button>
        </el-popconfirm>
        <el-button type="primary" class="common_btn-defalut" @click="submitMonitorBindEquip">确 定</el-button>
      </div>
    </el-drawer>
    <!-- 导入监测数据 -->
    <el-dialog :title="importNo==0?'监测数据导入':'基准数据导入'" :visible.sync="showImport" :close-on-click-modal="false"
               width="520px">
      <el-form ref="newUploadForm" :model="newUploadForm" label-width="80px" label-position="right">
        <el-row>
          <el-col :span="18">
            <el-form-item label="上传文件" prop="fileName">
              <el-input v-model="fileName" :readonly='true' placeholder="文件名" style="width:250px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-upload class="upload-demo" ref="upload" action="doUpload" :limit="1" :file-list="fileList"
                       :before-upload="beforeUpload">
              <el-button slot="trigger" type="primary" plain style="color:white;background:#1990FE">选择导入文件</el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-row>
          <el-button icon="el-icon-download" @click.stop="handleOutFile" size="mini" type="primary"
                     style="background:#1990FE ">导入模板下载
          </el-button>
        </el-row>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="cancleSub()">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateFormFile">确定</el-button>
      </span>
    </el-dialog>
    <x-loading v-show="isLoading"></x-loading>
  </div>
</template>

<script>
  import {
    getMonitorPointList,
    monitorPointSort,
    monitorDelete,
    importMonitorData, importBaseMonitorData,
    monitorSelect
  } from '@/services/model/project-info'
  import Enums from '@/utils/enums'
  import {store, actions} from '../work-point.store'
  import Format from '@/utils/format'
  import FormAddEdit from './modules/form-add-edit'
  import SensorRelation from './modules/sensor-relation'
  import XLoading from '@/components/animation/x-loading.vue'
  import Permission from '@/utils/permission'
  import {getLocalStorageItem} from "../../../utils/storage-helper";

  export default {
    mixins: [Enums],
    components: {FormAddEdit, SensorRelation, XLoading},
    data() {
      return {
        importNo: 0,//判断是导入基准数据还是导入数据

        rules: {
          mark: {required: true, message: '请输入‘删除’字符'},
        },
        monitorInfo: {},
        deleteConfirm: {
          mark: '',
          id: '',
        },
        monitorSortList: [],
        workAddId: 1,
        // 接口正在加载
        form: {
          page: 1,
          pageSize: 10,
          name: '',
          monitorType: null,
          projectId: this.$route.params.projectId,
          workPointId: ''
        },
        fileList: [],
        fileName: '',
        files: null,
        newUploadForm: {
          fileName: ''
        },
        newForm: false,
        isDelShowDialog: false,
        showBindingDevice: false,
        isShowDialog: false,
        isLoading: false,
        showImport: false,
        total: 0,
        tableList: [],
        workPointList2: [],
        monitorId: '',
        // 物质组成
        EnumProjectMonitorTypeList: [],
        slopeList: [],
        EnumWarningLevelList: [],
        selectListDeptTreeId: '',
        selectListRoadId: '',
        editMonitorTitle: '新增监测点',
      }
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        if (timer) {
          return Format(new Date(timer))
        }
        return ''
      },
      monitorMethod(val) {
        switch (val) {
          case 0:
            return '人工监测'
          case 1:
            return '自动监测'
          case 2:
            return '接入监测'
          case 3:
            return '滑动侧斜监测'
        }
      },
      gradeColor1(val) {
        switch (val) {
          case 2:
            return 'background-color:#0073b7;color:white'
          case 3:
            return 'background-color:#f39c12;color:white'
          case 4:
            return 'background-color:#ff851b;color:white'
          case 5:
            return 'background-color:#e43321;color:white'
          default:
            return 'background-color:#0DC26B;color:white'
        }
      },
      gradeColor(val) {
        switch (val) {
          case 0:
            return 'background-color:#0073b7'
          case 1:
            return 'background-color:#0DC26B'
          case 2:
            return 'background-color:#f39c12'
          case 3:
            return 'background-color:#f39c12'
        }
      },
      gradeMonitorType(val) {
        let iconMap = {
          1: 'iconshenbuweiyicexieyi',
          2: 'iconGNSS',
          3: 'iconlaxianweiyi',
          4: 'iconjiangyuliang',
          5: 'icondixiashuiwei',
          6: 'iconmaosuochuanganqi',
          7: 'iconjinglishuizhunyi2',
          8: 'iconqingjiao',
          9: 'iconxianxingtu',
          10: 'iconshidu',
          11: 'iconfengsufengxiangjiance',
          12: 'icondiyingli',
          13: 'iconzhendong',
          14: 'iconjianshiqicai01',
          15: 'iconGNSS',
          16: 'iconjianshiqicai01',
          17: 'iconzhendong',
          18: 'iconleida',
          19: 'iconshengguangbaojing',
          20: 'icona-fenzu1',
          21: 'iconzhendong',
          22: 'icondb_fill',
          23: 'iconzhendong',
        }
        return iconMap[val]
      },
    },
    computed: {
      projectDetail() {
        return store.projectInfo
      },
      // true  监测单位可操作
      isAuthority() {
        return this.$store.state.userInfo.unitType === 4
      },
    },
    methods: {
      cancleSub() { // 取消上传
        this.showImport = false
        this.fileName = ''
      },
      handleOutFile() { // 文件导出
        let path = ''
        if (this.importNo == 0) {
          if (this.monitorInfo.monitorType === 8) {
            path = '/statics/倾角数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 5) {
            path = '/statics/地下水位数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 4) {
            path = '/statics/降雨数据模板.xls'
          } else if (this.monitorInfo.monitorType === 6) {
            path = '/statics/锚索应力数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 10) {
            path = '/statics/温湿度数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 12) {
            path = '/statics/应力应变数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 13) {
            path = '/statics/振动数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 15) {
            path = '/statics/全站仪数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 1) {
            path = '/statics/深部数据导入模板.xls'
          } else if (this.monitorInfo.monitorType === 3) {
            path = '/statics/位移数据导入模板.xls'
          }
        } else {
          path = '/statics/深部基准数据导入模板.xls'
        }


        const {href} = this.$router.resolve({path: path})
        window.open(href)
      },
      // 确认导入文件
      validateFormFile() {
        this.$refs.newUploadForm.validate(valid => { // 是否通过 表单验证
          if (valid) {
            if (this.fileName === '') {
              this.$message({
                message: '请选择要上传的文件！',
                type: 'warning',
                showClose: true
              })
              return false
            }
            this.isLoading = true
            let fileFormData = new FormData()
            let action = this.importNo == 0 ? importMonitorData : importBaseMonitorData
            fileFormData.append('uploadFile', this.files, this.fileName) // 上传的文件

            action(this.monitorInfo.id, fileFormData).then(res => { // 上传请求
              if (res.code === 200) {
                this.fileName = ''
                this.showImport = false
                this.$notify({
                  type: 'success',
                  title: '提示',
                  message: '导入成功'
                })
                this.queryList()
              }
            })
          } else {
            this.$message({
              type: 'warning',
              message: '新增条件有误！',
              showClose: true
            })
          }
          this.isLoading = false
        })
      },
      beforeUpload(file) { // 上传前 文件校验
        this.files = file
        this.fileName = file.name
        return false // 返回false不会自动上传
      },
      // 判断权限
      hasPermission(permissionStr) {
        return Permission(this.$store.state.userInfo, permissionStr)
      },
      //拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
      allowDrop(draggingNode, dropNode, type) {
        //限制拖入节点内
        return type !== 'inner'
      },
      importData(row) {
        this.monitorInfo = row
        this.importNo = 0
        this.fileName = ''
        this.showImport = true
      },
      //导入基准数据
      importBaseData(row) {
        this.monitorInfo = row
        this.importNo = 1
        this.fileName = ''
        this.showImport = true

      },

      bindingDevice(row) {
        this.showBindingDevice = true
        if (row.bindEquipId) {
          this.$nextTick(() => {
            this.$refs.sensorRelation.handleEdit(row)
          })
        } else {
          this.$nextTick(() => {
            this.$refs.sensorRelation.handleAdd(row)
          })
        }
      },
      //打开排序
      async handleSortMonitorPoint() {
        let {data} = await monitorSelect({id: this.form.workPointId})
        this.monitorSortList = data.map(x => {
          return {id: x.id, weight: x.weight, label: x.name}
        })
        this.isShowDialog = true
      },
      async sortSubmit() {
        let name = []
        let i = this.monitorSortList.length
        //更新排序值
        this.monitorSortList.map(x => {
          x.weight = i
          name.push(x)
          i--
        })
        let res = await monitorPointSort(name)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '排序调整成功！'
          })
          this.isShowDialog = false
          this.queryList()
          this.reFlesh()
        }
      },
      unboundEquip() {
        this.$refs.sensorRelation.unboundEquip()
      },
      submitMonitorBindEquip() {
        this.$refs.sensorRelation.validateForm()
      },
      submitMonitor() {
        this.$refs.monitorPoint.validateForm()
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val
        this.queryList()
      },
      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val
        this.queryList()
      },
      //添加监测点和工点时刷新左侧导航菜单
      reFlesh(addSuccessInfo) {
        this.newForm = false
        this.showBindingDevice = false
        this.isDelShowDialog = false
        //监测点新增成功，没绑定设备，提示是否进行设备绑定
        // if (addSuccessInfo && !addSuccessInfo.bindEquipId && addSuccessInfo.isAutoRecord === 1) {
        //   addSuccessInfo.monitorTypeName = this.EnumProjectMonitorTypeList.filter(x => x.code === addSuccessInfo.monitorType)[0].name
        //   addSuccessInfo.warningFlagName = addSuccessInfo.warningFlag === 0 ? '手动预警' : '自动预警'
        //   this.$confirm('监测点更新成功，是否立刻绑定设备', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        //   }).then(() => {
        //     this.bindingDevice(addSuccessInfo)
        //   }).finally(() => {
        //     this.queryList()
        //     let projectId = this.$route.params?.projectId
        //     actions.queryWorkPointList(projectId)
        //     actions.queryProjectInfo(projectId)
        //   })
        // } else {
        this.queryList()
        let projectId = this.$route.params?.projectId
        actions.queryWorkPointList(projectId)
        actions.queryProjectInfo(projectId)
        // }
      },
      validateForm() {
        this.$refs.deleteConfirm.validate((valid) => {
          if (valid) {
            this.submitDelete()
          }
        })
      },
      async submitDelete() {
        let res = await monitorDelete(this.deleteConfirm)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '监测点删除成功'
          })
          this.reFlesh()
        }
      },
      // 处理删除
      async handleDelete(row) {
        this.isDelShowDialog = true
        this.deleteConfirm = {
          mark: '',
          id: row.id,
        }
        this.$nextTick(() => {
          this.$refs.deleteConfirm.clearValidate()
        })
      },
      // 添加监测点
      handleAddMonitorPoint() {
        this.editMonitorTitle = '新增监测点'
        this.newForm = true
        this.$nextTick(() => {
          this.$refs.monitorPoint.handleAdd(this.form.workPointId, this.form.projectId)
        })
      },
      // 编辑监测点
      handleEditMonitorPoint(row) {
        this.editMonitorTitle = '编辑监测点'
        this.newForm = true
        this.$nextTick(() => {
          this.$refs.monitorPoint.handleEdit(row)
        })
      },
      async queryList() {
        //没有项目名称，代表缓存清空（刷新页面 ），重新获取缓存
        if (!store.projectInfo.name) {
          const projectId = this.$route.params?.projectId
          await actions.queryWorkPointList(projectId)
          await actions.queryProjectInfo(projectId)
        }
        this.isLoading = true
        // 查询工点列表
        let res = await getMonitorPointList(this.form)
        this.tableList = res.data?.records || []
        this.form.page = Number(res.data?.current)
        this.total = Number(res.data?.total)
        this.isLoading = false
      },
      toControl(row) {
        this.$router.push({
          path: `/project/${row.projectId}/data-share?activeId=${row.id}&monitorType=${row.monitorType}&workPointId=${row.workPointId}`
        })
      },
    },
    created() {
      this.workPointList2 = getLocalStorageItem("workPoint_MonitorList")

    },
    mounted() {
      this.form.workPointId = this.workPointList2[0]?.id
      // 监测类型
      this.queryDictList(['EnumProjectMonitorType', 'EnumWarningLevel'], ['EnumProjectMonitorTypeList', 'EnumWarningLevelList'])
    },
    activated() {
      this.queryList()
    }
  }
</script>
<style scoped="scoped" lang="less">
  @import url('../common');

  /deep/ .el-tree-node__content {
    padding: 20px;
    font-size: 20px;
  }

  .custom-tree-node {
    text-align: center;
    display: block;
    font-size: 20px;
  }

  .monitor-type {
    color: #606266 !important;
    display: inline-block;
    margin-left: 0px;
    margin-right: 0px !important;
    padding: 0px !important;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: auto;
  }

  .warning_button {
    padding: 0px 5px !important;
    font-size: 12px;
    height: 20px !important;
  }

  .TypeName {
    /deep/ .el-button {
      color: black !important;
    }
  }

  .demo-drawer {

    .demo-drawer__content {
      height: 90%;
    }

    .demo-drawer__footer {
      bottom: 5%;
    }
  }

  .sensor_label {
    color: #1990FE;
    font-size: 12px;
    padding: 2px 0 3px 10px;
  }

  .sensor_info {
    color: #000000;
    padding: 2px 0 3px 10px;
    font-size: 10px;
  }

  .el-button--warning {
    color: #fff;
    background-color: #e6a23c;
    border-color: #e6a23c;
  }
</style>
